package com.lishem.bytebuffer;


import java.nio.ByteBuffer;

import static com.lishem.utils.ByteBufferUtil.debugAll;

/**
 * 粘包、半包练习
 */
public class TestByteBufferExam {

    public static void main(String[] args) {
        ByteBuffer source = ByteBuffer.allocate(32);
        //                     11            24
        source.put("Hello,world\nI'm zhangsan\nHo".getBytes());
        split(source);

        source.put("w are you?\nhaha!\n".getBytes());
        split(source);
    }

    public static void split(ByteBuffer source) {
        source.flip(); // 先切换成读模式
        for (int i = 0; i < source.limit(); ++i) {
            if (source.get(i) == '\n') {
                // 把这条完整消息存入新的ByteBuffer
                int length = i + 1 - source.position();
                ByteBuffer target = ByteBuffer.allocate(length);
                // 从source读，向target写
                for (int j = 0; j < length; j++) {
                    target.put(source.get());
                }
                debugAll(target);
            }
        }
        source.compact(); // 最后切回写模式
    }
}